﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;
//------------------------------------------------------------------------------
// The contents of this file are subject to the Mozilla Public License 1.1 (MPL); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://pritambaldota.com/licenses/license_MPL-1.1.html. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code belongs to Pritam Baldota's.
// The Initial Developer of the Original Code is Pritam Baldota.
// All Rights Reserved.
// 
// Contributor(s): Pritam Baldota. 
//------------------------------------------------------------------------------
namespace PritamBaldota.YouTube.Search
{
    public class YouTubeServiceManager
    {
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchText">Text to Search</param>
        /// <param name="startPageIndex">Minimum 1 to 50</param>
        /// <param name="maxResult">Maximum 50</param>
        /// <returns></returns>
        public static System.Collections.Generic.List<YouTube> SearchVideos(string searchText, int startPageIndex,int maxResult)
        {
            if (startPageIndex < 1)
                startPageIndex = 1;
            if (maxResult > 50)
                maxResult = 50;
            else if (maxResult < 1)
                maxResult = 1;

            System.Collections.Generic.List<YouTube> res = new List<YouTube>();
            XmlDocument oXmlDoc = new XmlDocument();
            string feedURL = "http://gdata.youtube.com/feeds/api/videos?vq=" + searchText + "&orderby=published&start-index=" + startPageIndex + "&max-results="+maxResult;
            try
            {
                #region Object Creation and Declaration
                StringBuilder title = new StringBuilder();
                StringBuilder link = new StringBuilder();
                StringBuilder description = new StringBuilder();
                string id = "", vurl;
                XmlNodeList nodes = oXmlDoc.ChildNodes;
                byte FeedType = 2;//1- RSS 2.0, 2- ATOM 1.0, 3- RSS 1.0
                #endregion

                #region Load Feed URL to XML Document
                oXmlDoc.Load(feedURL);
                XmlNode rootnode = oXmlDoc.ChildNodes[0].NodeType == XmlNodeType.XmlDeclaration ? oXmlDoc.ChildNodes[1] : oXmlDoc.ChildNodes[0];
                //nodes = oXmlDoc.ChildNodes[1].SelectNodes("entry");
                #endregion
                foreach (XmlNode node in rootnode.ChildNodes)
                {
                    if (node.Name != "entry") continue;
                    YouTube youtube = new YouTube();
                    foreach (XmlNode chnode in node.ChildNodes)
                    {
                        if (chnode.Name == "id")
                        {
                            if (chnode.FirstChild != null)
                            youtube.Id = chnode.FirstChild.Value.Substring(chnode.FirstChild.Value.LastIndexOf('/') + 1);
                        }
                        else if (chnode.Name == "title")
                        {
                            if (chnode.FirstChild != null)
                            youtube.Title = chnode.FirstChild.Value;
                        }
                        else if (chnode.Name == "content")
                        {
                            if(chnode.FirstChild!=null)
                            youtube.Description =   chnode.FirstChild.Value;
                        }
                        else if (chnode.Name == "link")
                        {
                            if (chnode.Attributes["rel"] != null)
                            {
                                if (chnode.Attributes["rel"].Value.ToLower().Trim().Equals("alternate"))
                                    youtube.VideoUrl = chnode.Attributes["href"].Value.Trim();
                            }
                            else
                            {
                                youtube.VideoUrl = chnode.Attributes["href"].Value.Trim();
                            }
                        }

                    }
                    
                    //0.jpg 320 x 240, 1.jpg 130 x 97
                    youtube.Thumb = "http://img.youtube.com/vi/" + youtube.Id + "/0.jpg";
                    res.Add(youtube);
                }
                return res;
               
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return null;
        }
        internal static string GetYouTubeURL(string src)
        {
            string rawStr = GetPageContent(src);
            string videoId = "", t = "";
            rawStr = rawStr.Substring(rawStr.IndexOf("video_id", StringComparison.CurrentCultureIgnoreCase), 150);
            string[] keyvalues = rawStr.Split(new char[] { ',' });

            foreach (string str in keyvalues)
            {
                string res = "";
                if (str.IndexOf("video_id") != -1)
                {
                    res = str.Split(new char[] { ':' })[1];
                    res = res.Replace("\"", "");
                    res = res.Replace(",", "");
                    res = res.Trim();
                    videoId = res;
                }
                else if (str.IndexOf("\"t\"") != -1)
                {
                    res = str.Split(new char[] { ':' })[1];
                    res = res.Replace("\"", "");
                    res = res.Replace(",", "");
                    res = res.Trim();
                    t = res;
                }
            }
            //return "ORig" + rawStr + "************* VID " + videoId + "    t  " + t;
            return "http://www.youtube.com/get_video.php?video_id=" + videoId + "&t=" + t;
                    }
        internal static string GetPageContent(string url)
        {
            String content = "";
            try
            {
                WebRequest wreq;
                WebResponse wres;
                StreamReader sr;
                wreq = HttpWebRequest.Create(url);
                wres = wreq.GetResponse();

                sr = new StreamReader(wres.GetResponseStream());
                content = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception)
            {

                throw new ArgumentException("Unable to get the Content");
            }

            return content;
        }
    }
}
